package com.execdemo.demoorderservice.rabbitmq;

import com.alibaba.fastjson.JSON;
import com.execdemo.demoorderservice.domain.OrderInfo;
import com.execdemo.demoorderservice.enumerate.Result;
import com.execdemo.demoorderservice.redis.impl.myRedisLock;
import com.execdemo.demoorderservice.service.OrderlistReviewService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

import java.util.concurrent.Executors;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

@Slf4j
@Component
public class MessageConsumer {
    @Autowired
    OrderlistReviewService orderlistReviewService;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;


//    private final List<Orderlist> orderlistMq = new ArrayList<>();


    /**
     * 消费者
     * 监听RabbitMQ队列中的消息并异步处理
     * 该方法接收一个字符串消息，将其解析为OrderInfo对象，并调用订单验证服务进行处理
     *
     * @param message 从mq队列中接收到的消息，以字符串形式表示
     */
    @RabbitListener(queues = "mq")
//    @SendTo
    public void receiveMessage(String message) {


        myRedisLock lock = new myRedisLock("order" + JSON.parseObject(message, OrderInfo.class).getCode(), stringRedisTemplate);

        boolean isLock =lock.tryLock(5);
        if (!isLock) {
            log.info("订单正在处理中，请稍后...");
            return;
        }

        try {
            asyncReceiveMessage(message);
        } finally {
            lock.unlock();
        }


        /*// 创建一个ThreadPoolExecutor线程池
        // 核心线程数为20，最大线程数为30，空闲线程存活时间为60秒
        // 使用LinkedBlockingQueue作为工作队列，队列大小为10
        // 使用Executors.defaultThreadFactory()创建线程工厂
        // 拒绝执行的处理策略为DiscardOldestPolicy，即丢弃最旧的任务
        ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(
                20,
                30,
                60L,
                TimeUnit.SECONDS,
                new LinkedBlockingQueue<>(10),
                Executors.defaultThreadFactory(),
                new ThreadPoolExecutor.DiscardOldestPolicy()
        );*/
//        Result result = Result.fail();
//        return result;

        // return CompletableFuture.completedFuture(order);
    }

    @Async("threadPoolExecutor")
    public void asyncReceiveMessage(String message) {

        try {
            log.info("从RabbitMQ队列中取得消息 : " + message);
            //
            // 将接收到的消息解析为OrderInfo对象
            OrderInfo orderHeader = JSON.parseObject(message, OrderInfo.class);
            // 调用订单验证服务方法处理解析后的订单信息
            orderlistReviewService.mqConsumer2(orderHeader);

//            System.out.println("Received message: " + orderlistMq);
        } catch (Exception e) {

            // 打印异常信息并记录错误日志
            e.printStackTrace();
            log.error("Failed to receive message: " + message, e);
        }
    }


/*    public List<Orderlist> getOrderMq() {

        log.info("Received controller message: " + orderlistMq);
    	return orderlistMq;
    }*/
}
